<?php

namespace business\elasticsearch\services;

use business\elasticsearch\models\BigDataMohurdProjectModel;

class BigDataMohurdProjectService
{
    public function getDataList(
        $keyword,
        $province,
        $city,
        $area,
        $companyType,
        $companyArea,
        $isPriceGtAvg,
        $prjPropertyNum,
        $prjTypeNum,
        $allInvestStart,
        $allInvestEnd,
        $startDateStart = '',
        $startDateEnd = '',
        $completeDateStart = '',
        $completeDateEnd = '',
        $createdTime = '',
        $tags = [],
        $organizingCode = [],
        $page = 1,
        $pageSize = 20)
    {
        $condition = $this->constructCondition(
            $keyword,
            $province,
            $city,
            $area,
            $companyType,
            $companyArea,
            $isPriceGtAvg,
            $prjPropertyNum,
            $prjTypeNum,
            $allInvestStart,
            $allInvestEnd,
            $startDateStart,
            $startDateEnd,
            $completeDateStart,
            $completeDateEnd,
            $createdTime,
            $tags,
            $organizingCode
        );

        $query = BigDataMohurdProjectModel::find()->query($condition);

        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "prj_name" => new \stdClass(),
                "build_corp_name" => new \stdClass()
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['start_date' => SORT_DESC, 'id' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $searchData = $query->createCommand()->search();

        $result = ['total' => 0, 'list' => []];
        if (!empty($searchData)) {
            $data = $searchData["hits"]["hits"];
            $total = $searchData["hits"]["total"];

            //数据处理
            $result['total'] = $total;
            foreach ($data as $dv) {
                $tmp = $dv['_source'];
                $tmp['nameSuggest'] = $tmp['prj_name'];
                if (!empty($dv['highlight'])) {
                    foreach ($dv['highlight'] as $key => $value) {
                        $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                    }
                }

                if (empty($tmp['developer_id']) || empty($tmp['developer_logo'])) {
                    $tmp['developer_id'] = '';
                    $tmp['developer_logo'] = '';
                }
                $tmp = $this->dealResultItem($tmp);

                $result['list'][] = $tmp;
            }
        }

        return $result;
    }

    private function constructCondition(
        $keyword = [],
        $province = [],
        $city = [],
        $area = [],
        $companyType = [],
        $companyArea = [],
        $isPriceGtAvg = [],
        $prjPropertyNum = [],
        $prjTypeNum = [],
        $allInvestStart = '',
        $allInvestEnd = '',
        $startDateStart = '',
        $startDateEnd = '',
        $completeDateStart = '',
        $completeDateEnd = '',
        $createdTime = '',
        $tags = [],
        $organizingCode = []
    )
    {
        $query = [];
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
        $must = [];
        $query['function_score']['query']['bool']['must'] = &$must;

        //项目关键词
        if (!empty($keyword)) {
            $keyShould = [];
            $must[] = ['bool' => ['should' => &$keyShould]];

            foreach ($keyword as $k) {

                $projectBool = [];
                $projectBool[] = [
                    'match_phrase' => ['prj_name' => ["query" => $k, "boost" => 3, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $projectBool]];

                $developerBool = [];
                $developerBool[] = [
                    'match_phrase' => ['build_corp_name' => ["query" => $k, "boost" => 3, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $developerBool]];

            }
        }
        if (!empty($organizingCode)) {
            $must[] = ["terms" => ['organizing_code.keyword' => $organizingCode]];
        }


        // 省市
        if (!empty($province)) {
            $must[] = ["terms" => ['province_code' => $province]];
        }
        if (!empty($city)) {
            $must[] = ["terms" => ['city_code' => $city]];
        }

        //地区
        if (!empty($area)) {
            $shouldArea = [];
            $must[] = ['bool' => ['should' => &$shouldArea]];
            $shouldArea[] = ["terms" => ['province_code' => $area]];
            $shouldArea[] = ["terms" => ['city_code' => $area]];
        }

        //企业地区
        if (!empty($companyArea)) {
            $shouldCompanyArea = [];
            $must[] = ['bool' => ['should' => &$shouldCompanyArea]];
            $shouldCompanyArea[] = ["terms" => ['build_corp_province_code' => $companyArea]];
            $shouldCompanyArea[] = ["terms" => ['build_corp_city_code' => $companyArea]];
        }

        //企业类型
        if (!empty($companyType)) {
            $must[] = ["terms" => ['company_type_label' => $companyType]];
        }


        //高端项目标签
        if (!empty($isPriceGtAvg)) {
            $must[] = ["terms" => ['is_price_gt_avg' => $isPriceGtAvg]];
        }


        // 建筑性质
        if (!empty($prjPropertyNum)) {
            $must[] = ["terms" => ['prj_property_num' => $prjPropertyNum]];
        }

        // 工程用途
        if (!empty($prjTypeNum)) {
            $must[] = ["terms" => ['prj_type_num' => $prjTypeNum]];
        }

        // 总投资
        $allInvest = [];
        if (!empty($allInvestStart)) {
            $allInvest['gte'] = $allInvestStart;
        }
        if (!empty($allInvestEnd)) {
            $allInvest['lt'] = $allInvestEnd;
        }
        if (!empty($allInvest)) {
            $must[] = ['range' => ['all_invest' => $allInvest]];
        }

        // 立项、开工时间
        $startDate = [];
        if (!empty($startDateStart)) {
            $startDate['gte'] = date('Y-m-d', strtotime($startDateStart)) . " 00:00:00";
        }
        if (!empty($startDateEnd)) {
            $startDate['lt'] = date('Y-m-d', strtotime($startDateEnd)) . " 23:59:59";
        }
        if (!empty($startDate)) {
            $must[] = ['range' => ['start_date' => $startDate]];
        }

        // 竣工时间
        $completeDate = [];
        if (!empty($completeDateStart)) {
            $completeDate['gte'] = date('Y-m-d', strtotime($completeDateStart)) . " 00:00:00";
        }
        if (!empty($completeDateEnd)) {
            $completeDate['lt'] = date('Y-m-d', strtotime($completeDateEnd)) . " 23:59:59";
        }
        if (!empty($completeDate)) {
            $must[] = ['range' => ['complete_date' => $completeDate]];
        }

        if (!empty($createdTime)) {
            $dateRange = [];
            $dateRange['from'] = $createdTime;
            $dateRange['to'] = date('Y-m-d H:i:s', time());
            $must[] = ['range' => ['modified_on' => $dateRange]];
        }

        //企业标签
        if (!empty($tags)) {
            $tagShould = [];
            foreach ($tags as $k => $v) {
                if (!empty($v)) {
                    $tagShould[] = ['term' => [$k => $v]];
                }
            }
            $must[] = [
                'bool' => ['should' => $tagShould]
            ];
        }

        return $query;
    }


    public function guessNames($keyword, $pageSize)
    {
        $page = 1;

        $query = [];
        if (!empty($keyword)) {
            $query['function_score']['query']['bool']['must'][] = [
                'match_phrase' => ['prj_name' => $keyword]
            ];
        }

        $query = BigDataMohurdProjectModel::find()
            ->query($query);

        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "prj_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        //数据处理
        $result = [];
        foreach ($data as $dv) {
            $item = array();
            $tmp = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['project_name'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $item['title'] = $tmp['prj_name'];
            $item['titleHL'] = $tmp['prj_nameHL'];
            $result[] = $item;
        }
        return $result;
    }

    /**
     * 显示赋值，因为 es 的值如果为 null 会没有字段
     * @param $item
     * @return array
     */
    private function dealResultItem($item)
    {
        $tmp["id"] = $item["id"] ?? "";
        $tmp["prj_num"] = $item["prj_num"] ?? "";
        $tmp["province_prj_num"] = $item["province_prj_num"] ?? "";
        $tmp["prj_name"] = $item["prj_name"] ?? "";
        $tmp["prj_type_num"] = $item["prj_type_num"] ?? "";
        $tmp["province"] = $item["province"] ?? "";
        $tmp["province_code"] = $item["province_code"] ?? "";
        $tmp["city"] = $item["city"] ?? "";
        $tmp["city_code"] = $item["city_code"] ?? "";
        $tmp["county"] = $item["county"] ?? "";
        $tmp["address"] = $item["address"] ?? "";
        $tmp["location_x"] = $item["location_x"] ?? "";
        $tmp["location_y"] = $item["location_y"] ?? "";
        $tmp["prj_approval_num"] = $item["prj_approval_num"] ?? "";
        $tmp["prj_approval_level_num"] = $item["prj_approval_level_num"] ?? "";
        $tmp["prj_approval_depart"] = $item["prj_approval_depart"] ?? "";
        $tmp["prj_approval_date"] = $item["prj_approval_date"] ?? "";
        $tmp["build_corp_name"] = $item["build_corp_name"] ?? "";
        $tmp["organizing_code"] = $item["organizing_code"] ?? "";
        $tmp["company_type_label"] = $item["company_type_label"] ?? "";
        $tmp["top_developer_name"] = $item["top_developer_name"] ?? "";
        $tmp["top_organizing_code"] = $item["top_organizing_code"] ?? "";
        $tmp["top_company_type_label"] = $item["top_company_type_label"] ?? "";
        $tmp["build_plan_num"] = $item["build_plan_num"] ?? "";
        $tmp["project_plan_num"] = $item["project_plan_num"] ?? "";
        $tmp["fund_source"] = $item["fund_source"] ?? "";
        $tmp["national_percentage"] = $item["national_percentage"] ?? "";
        $tmp["all_invest"] = $item["all_invest"] ?? 0;
        $tmp["all_area"] = $item["all_area"] ?? 0;
        $tmp["all_length"] = $item["all_length"] ?? "";
        $tmp["prj_size"] = $item["prj_size"] ?? "";
        $tmp["prj_property_num"] = $item["prj_property_num"] ?? "";
        $tmp["prj_function_num"] = $item["prj_function_num"] ?? "";
        $tmp["prj_two_dim_code"] = $item["prj_two_dim_code"] ?? "";
        $tmp["is_major"] = $item["is_major"] ?? "";
        $tmp["begin_date"] = $item["begin_date"] ?? "";
        $tmp["end_date"] = $item["end_date"] ?? "";
        $tmp["jz_jn_info"] = $item["jz_jn_info"] ?? "";
        $tmp["cx_xm_info"] = $item["cx_xm_info"] ?? "";
        $tmp["check_depart_name"] = $item["check_depart_name"] ?? "";
        $tmp["check_person_name"] = $item["check_person_name"] ?? "";
        $tmp["data_source"] = $item["data_source"] ?? "";
        $tmp["data_source_name"] = $item["data_source_name"] ?? "";
        $tmp["data_level"] = $item["data_level"] ?? "";
        $tmp["data_level_value"] = $item["data_level_value"] ?? "";
        $tmp["is_fake"] = $item["is_fake"] ?? "";
        $tmp["fake_corp_name"] = $item["fake_corp_name"] ?? "";
        $tmp["create_date"] = $item["create_date"] ?? "";
        $tmp["md5_id"] = $item["md5_id"] ?? "";
        $tmp["update_time"] = $item["update_time"] ?? "";
        $tmp["status"] = $item["status"] ?? "";
        $tmp["md5_data"] = $item["md5_data"] ?? "";
        $tmp["conscorp_name"] = $item["conscorp_name"] ?? "";
        $tmp["contract_date"] = $item["contract_date"] ?? "";
        $tmp["release_date"] = $item["release_date"] ?? "";
        $tmp["licence_check_depart_name"] = $item["licence_check_depart_name"] ?? "";
        $tmp["builder_licence_num"] = $item["builder_licence_num"] ?? "";
        $tmp["b_date"] = $item["b_date"] ?? "";
        $tmp["e_date"] = $item["e_date"] ?? "";
        $tmp["tender_result_date"] = $item["tender_result_date"] ?? "";
        $tmp["contact_cnt"] = $item["contact_cnt"] ?? "";
        $tmp["bidding_cnt"] = $item["bidding_cnt"] ?? "";
        $tmp["contract_cnt"] = $item["contract_cnt"] ?? "";
        $tmp["construction_cnt"] = $item["construction_cnt"] ?? "";
        $tmp["license_cnt"] = $item["license_cnt"] ?? "";
        $tmp["completion_check_cnt"] = $item["completion_check_cnt"] ?? "";
        $tmp["completion_record_cnt"] = $item["completion_record_cnt"] ?? "";
        $tmp["about_company_cnt"] = $item["about_company_cnt"] ?? "";
        $tmp["price"] = $item["price"] ?? "";
        $tmp["price_city_avg"] = $item["price_city_avg"] ?? "";
        $tmp["is_price_gt_avg"] = $item["is_price_gt_avg"] ?? "";
        $tmp["modified_on"] = $item["modified_on"] ?? "";
        $tmp["developer_top_100_label"] = $item["developer_top_100_label"] ?? "";
        $tmp["new_area_expand_label"] = $item["new_area_expand_label"] ?? "";
        $tmp["new_decorate_expand_label"] = $item["new_decorate_expand_label"] ?? "";
        $tmp["new_land_usage_expand_label"] = $item["new_land_usage_expand_label"] ?? "";
        $tmp["price_gt_avg_label"] = $item["price_gt_avg_label"] ?? "";
        $tmp["urban_investment_label"] = $item["urban_investment_label"] ?? "";
        $tmp["company_province_code"] = $item["company_province_code"] ?? "";
        $tmp["company_city_code"] = $item["company_city_code"] ?? "";
        $tmp["conscorp_organizing_code"] = $item["conscorp_organizing_code"] ?? "";
        $tmp["start_date"] = $item["start_date"] ?? "";
        $tmp["complete_date"] = $item["complete_date"] ?? "";
        $tmp["nameSuggest"] = $item["nameSuggest"] ?? "";
        $tmp["developer_id"] = $item["developer_id"] ?? "";
        $tmp["developer_logo"] = $item["developer_logo"] ?? "";
        $tmp["prj_nameHL"] = $item["prj_nameHL"] ?? "";
        $tmp["build_corp_nameHL"] = $item["build_corp_nameHL"] ?? "";
        return $tmp;
    }

}